<template>
  <div class="activity-edit">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择开始时间"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择结束时间"
        />
      </el-form-item>
      <el-form-item label="活动地点" prop="location">
        <el-input v-model="form.location" />
      </el-form-item>
      <el-form-item label="活动类型" prop="type">
        <el-select v-model="form.type" placeholder="选择活动类型">
          <el-option
            v-for="item in activityTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="参与人数" prop="maxParticipants">
        <el-input-number
          v-model="form.personNum"
          :min="1"
          :max="1000"
        />
      </el-form-item>
      <el-form-item label="活动描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          rows="4"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import myAxios from "../../../plugins/myAxios.js";

const route = useRoute()
const router = useRouter()

// 使用 ref 来存储活动ID，方便监听变化
const activityId = ref(route.query.id || route.params.id)

// 监听路由参数变化
watch(
  () => route.query.id || route.params.id,
  (newId) => {
    activityId.value = newId
    if (newId) {
      loadActivityInfo(newId)
    }
  }
)

const formRef = ref()
const form = reactive({
  name: '',
  startTime: '',
  endTime: '',
  location: '',
  type: '',
  personNum: 0,
  description: '',
  images: []
})

const rules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && form.startTime && value <= form.startTime) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ]
}

const activityTypes = [
  { label: '文化活动', value: 'culture' },
  { label: '体育活动', value: 'sports' },
  { label: '志愿服务', value: 'volunteer' },
  { label: '学术讲座', value: 'academic' }
]

const handleImageChange = (file) => {
  // 处理图片上传
  console.log('Selected file:', file)
}

// 重置表单数据
const resetFormData = () => {
  form.name = ''
  form.startTime = ''
  form.endTime = ''
  form.location = ''
  form.type = ''
  form.personNum = 0
  form.description = ''
  form.images = []
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const activityData = {
          id: activityId.value,
          name: form.name,
          startTime: form.startTime,
          endTime: form.endTime,
          location: form.location,
          type: form.type,
          personNum: form.personNum,
          description: form.description
        }

        await myAxios.post('/admin/activity/update', activityData)
        ElMessage.success('活动信息更新成功')

        // 重置表单的校验结果
        formEl.resetFields()
        // 重置表单数据
        resetFormData()


        // 跳转到列表页面
        router.push('/admin/activity/list')
      } catch (error) {
        console.error('更新活动信息失败:', error)
        ElMessage.error(typeof error === 'string' ? error : '更新活动信息失败')
      }
    } else {
      console.log('表单验证失败:', fields)
      ElMessage.error('请完善表单信息')
    }
  })
}

// 重置按钮点击事件处理
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  resetFormData()
}

// 加载活动信息
const loadActivityInfo = async (id) => {
  if (!id) {
    ElMessage.error('活动ID不能为空')
    return
  }

  try {
    console.log('开始加载活动信息，ID:', id)
    const data = await myAxios.get('/admin/activity/get?id=' + id)
    console.log('获取到的活动数据:', data)

    // 由于myAxios已经处理了响应拦截，这里直接使用返回的data
    form.name = data.name
    form.startTime = data.startTime
    form.endTime = data.endTime
    form.location = data.location
    form.type = data.type
    form.description = data.description
    form.personNum = data.personNum

    ElMessage.success('活动信息加载成功')
  } catch (error) {
    console.error('加载活动信息失败:', error)
    ElMessage.error(typeof error === 'string' ? error : '加载活动信息失败')
    router.push('/admin/activity/list')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  console.log('组件挂载，活动ID:', activityId.value)
  if (activityId.value) {
    loadActivityInfo(activityId.value)
  }
})

</script>

<style scoped>
.activity-edit {
  max-width: 800px;
  margin: 20px auto;
}
.activity-uploader {
  margin-top: 10px;
}
</style>
